import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import { Modal } from 'view-design'
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = process.env.VUE_APP_API_URL
    this.queue = {}
  }

  getInsideConfig (options) {
   
    var headers = {}
    if (options.headers) {
      headers = options.headers
      headers.token = localStorage.getItem('token')
    } else {
      headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        token: localStorage.getItem('token')
      }
    }
    const config = {
      baseURL: this.baseUrl,
      headers: headers
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
  }

  /**
   * 格式化传入的数据
   */
  formatReqData (method, data, config) {
    const upperCaseMethod = method.toUpperCase()
    let k = ''
    let postData
    switch (upperCaseMethod) {
      case 'POST':
      case 'PUT':
      case 'DELETE':
        k = 'data'
        if (config.headers['Content-Type'] == 'application/json') {
          postData = data
        } else {
          postData = qs.stringify(data)
        }

        break
      case 'GET':
        k = 'params'
        postData = data
        break
      default:
        throw new Error('不认识的methods')
    }
    return {
      k,
      postData
    }
  }

  /**
   * 回到登陆
   */
  toLogin () {
    router.push({
      name: 'login'
    })
  }

  errorMsg (message) {
    setTimeout(function(){
      Modal.error({
        title: '系统提示',
        content: message
      })
    },300)
    
  }

  /**
   * 错误处理
   */
  async errorCode (status, message) {
    console.log(status, message)
    switch (status) {
      case 400: // 报错
        this.errorMsg(message)
        break
      case 401: // 登陆超时
        this.toLogin()
        break
      case 403: // 没权限
        router.push({
          name: 'error_403'
        })
        break
      case 404: // 404
        router.push({
          name: 'error_404'
        })
        break
      case 405:
        this.errorMsg('系统错误，请求方法错误！')
        break
      case 422: // 登陆超时
        this.errorMsg(message)
        break
      case 500: // 系统错误
        this.errorMsg(message || '系统繁忙，请稍后再试！')
        // router.push({
        //     name: 'error_500'
        // });
        break
      default:
        this.errorMsg(message)
        break
    }
  }

  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        this.queue[url] = true
        const { method, data } = config
        const { k, postData } = this.formatReqData(method, data, config)
        config[k] = postData
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url)
        const { data } = res
        if (data.code == 200) {
          return data
        } else {
          this.errorCode(data.code, data.msg)
          return Promise.reject(data)
        }
      },
      error => {
        const {
          status,
          data: { msg }
        } = error
        this.errorCode(status, msg)
        return Promise.reject(error)
      }
    )
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(options), options)
    if(options.data&&JSON.stringify(options.data)!='{}'){
      options.data.token=localStorage.getItem('token')
      options.data.timestamp=new Date().getTime()
      options.data.version='1.0'
      options.data.clientId='1000'
    }

    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
